package me.zhengjie.modules.sync.processing;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.service.property.domain.Estate;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import com.qiaofang.applet.service.property.service.EstateService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import me.zhengjie.utils.ImageUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
 * 楼盘数据处理
 * */
@Slf4j
@Service
public class EstateSyncProcessing extends ProcessingBase {

    public EstateSyncProcessing() {
        setDataType(SyncTypeEnum.ESTATE.getSyncType());
    }

    @Autowired
    EstateService estateService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void processing(SyncDataQueue syncDataQueue) {
        String batchContent = syncDataQueue.getBatchContent();
        List<Estate> list = JSON.parseArray(batchContent, Estate.class);
        if (null == list) {
            log.info("processing Estate is null");
            return;
        }
        list.stream().forEach(item -> {
            saveEstate(item, syncDataQueue);
        });
    }

    private void saveEstate(Estate item, SyncDataQueue syncDataQueue) {
        String estateUniqueUuid = syncDataQueue.getCompanyUuid() + "_" + item.getEstateUuid();
        Estate estate = estateService.findByEstateUniqueUuid(estateUniqueUuid);
        if (!Objects.isNull(item.getDeleted()) && item.getDeleted()) {
            if (!Objects.isNull(estate)) {
                estateService.deleteById(estate.getId());
            }
            return;
        }
        if (Objects.isNull(estate)) {
            estate = new Estate();
            estate.setRentNum(0);
            estate.setSaleNum(0);
        }
        //复制属性
        String[] ignoreProperties = new String[]{"id", "createBy", "saleNum", "rentNum", "updateBy", "createTime", "updateTime"};
        BeanUtils.copyProperties(item, estate, ignoreProperties);
        estate.setEstateUniqueUuid(estateUniqueUuid);
        estate.setCompanyUuid(syncDataQueue.getCompanyUuid());
        estate.setCityCode(syncDataQueue.getCityCode());
        estate.setCorporationCode(syncDataQueue.getCorporationCode());
        estate.setUpdateTime(new Date());
        estate.setRelationUpdate(true);
        estate.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        //增加封面图标识
        if (!StringUtils.isEmpty(item.getPhotoUrl())){
            estate.setCoverPicture(true);
        } else {
            estate.setCoverPicture(false);
        }
        replaceDomain(estate);
        //删除楼盘图片水印缓存
        redisUtil.hdel(RedisKeyUtil.getPropertyWaterMarkKey(syncDataQueue.getCompanyUuid()), estateUniqueUuid);
        try {
            estateService.save(estate);
        } catch (Exception e) {
            log.error("saveEstate error ", e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(estate), e.getMessage(), syncDataQueue);
        }
    }

    //替换域名
    private void replaceDomain(Estate estate) {
        String photoUrl = estate.getPhotoUrl();
        if (StringUtils.isEmpty(photoUrl)) {
            return;
        }
        if ((photoUrl.startsWith(ImageUtil.HTTP) || photoUrl.startsWith(ImageUtil.HTTPS)) && photoUrl.contains(ImageUtil.DISCARD_IMAGE_URL)) {
            photoUrl = StringUtils.replace(estate.getPhotoUrl(), ImageUtil.DISCARD_IMAGE_URL, ImageUtil.IMAGE_URL);
        } else {
            photoUrl = ImageUtil.HTTP + ImageUtil.IMAGE_URL + "/" + photoUrl;
        }
        estate.setPhotoUrl(photoUrl);
    }
}
